from flask import request, jsonify
from ..models.user import User
from ..extensions import db
from ..utils.security import generate_password_hash, check_password
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from datetime import datetime
from ..utils.response import pagination, error, success

def register(data):
    """注册用户"""
    
    # 检查必填字段
    required_fields = ['email', 'phone', 'password']
    for field in required_fields:
        if field not in data:
            return error(f"{field} is required", 400)
    
    # 检查手机号是否已存在
    if User.query.filter_by(phone=data['phone']).first():
        return error("Phone number already exists", 400)
    
    # 检查邮箱是否已存在（如果提供了邮箱）
    if data.get('email') and User.query.filter_by(email=data['email']).first():
        return error("Email already exists", 400)
    
    # 创建用户
    user = User(
        name="默认用户",
        phone=data['phone'],
        email=data.get('email'),
        password=generate_password_hash(data['password']),
        is_disabled=data.get('is_disabled', False)
    )
    
    # 处理生日字段
    if data.get('birthday'):
        try:
            user.birthday = datetime.strptime(data['birthday'], '%Y-%m-%d').date()
        except ValueError:
            return error("Invalid birthday format, should be YYYY-MM-DD", 400)
    
    db.session.add(user)
    db.session.commit()
    
    return success(user.to_dict(), "User created successfully")

def login(data):
    phone = data.get("phone")
    password = data.get("password")
    
    if not phone or not password:
        return error("Phone and password are required", 400)
    
    user = User.query.filter_by(phone=phone).first()
    if not user or not check_password(user.password, password):
        return error("Invalid credentials", 401)
    
    if user.is_disabled:
        return error("User is disabled", 403)
    
    access_token = create_access_token(identity=user.id)
    return success(user.to_dict(), "Login successful")


def get_user(user_id):
    # 获取当前登录用户的ID
    current_user_id = get_jwt_identity()
    
    # 查找指定用户
    user = User.query.get(user_id)
    if not user:
        return error("User not found", 404)
    
    return success(user.to_dict(), "User found") 

from sqlalchemy import text

def get_all_users(data):
    """获取所有用户，支持分页 + 动态筛选（原生 SQL）"""
    try:
        # 分页参数
        page = int(data.get('page', 1))
        page_size = int(data.get('page_size', 10))
        page = max(page, 1)
        page_size = min(max(page_size, 1), 100)
        offset = (page - 1) * page_size

        # ---- 动态筛选条件 ----
        filters = []
        params = {}

        # 示例筛选字段（你可以按实际需要扩展）
        if data.get('name'):
            filters.append("u.name LIKE :name")
            params["name"] = f"%{data['name']}%"

        if data.get('phone'):
            filters.append("u.phone LIKE :phone")
            params["phone"] = f"%{data['phone']}%"

        if data.get('is_disabled') is not None:
            filters.append("u.is_disabled = :is_disabled")
            params["is_disabled"] = data['is_disabled']

        if data.get('house_id'):
            filters.append("u.house_id = :house_id")
            params["house_id"] = data['house_id']

        if data.get('parking_id'):
            filters.append("u.parking_id = :parking_id")
            params["parking_id"] = data['parking_id']

        # 组装 WHERE 子句
        where_clause = ""
        if filters:
            where_clause = "WHERE " + " AND ".join(filters)

        # ---- 统计总数 ----
        count_sql = text(f"""
            SELECT COUNT(*) AS total
            FROM users u
            LEFT JOIN parking_spaces p ON u.parking_id = p.id
            LEFT JOIN houses h ON u.house_id = h.id
            {where_clause}
        """)
        total = db.session.execute(count_sql, params).scalar() or 0

        # ---- 查询分页数据 ----
        data_sql = text(f"""
            SELECT
                u.id AS user_id,
                u.name AS user_name,
                u.phone,
                u.email,
                u.birthday,
                u.is_disabled,
                h.name AS house_name,
                p.location AS parking_location
            FROM users u
            LEFT JOIN parking_spaces p ON u.parking_id = p.id
            LEFT JOIN houses h ON u.house_id = h.id
            {where_clause}
            ORDER BY u.id DESC
            LIMIT :limit OFFSET :offset
        """)
        params.update({"limit": page_size, "offset": offset})

        rows = db.session.execute(data_sql, params).fetchall()
        users = [dict(row._mapping) for row in rows]

        return pagination(
            items=users,
            total=total,
            msg='获取成功',
            code=200
        )

    except Exception as e:
        print(f"Error in get_all_users: {str(e)}")
        return error('获取失败', 500)

def update_user(data):
    # 查找要更新的用户
    user = User.query.get(data.get('id'))
    if not user:
        return error('用户不存在', 404)
    
    # 更新用户信息
    if data.get('name'):
        user.name = data['name']
    
    if data.get('email'):
        # 检查邮箱是否已被其他用户使用
        if User.query.filter(User.email == data['email'], User.id != user.id).first():
            return error('邮箱已被使用', 400)
        user.email = data['email']
    
    # 处理生日字段
    if data.get('birthday'):
        try:
            user.birthday = datetime.strptime(data['birthday'], '%Y-%m-%d').date()
        except ValueError:
            return error('生日格式错误，应为YYYY-MM-DD', 400)
    
    # 更新密码（如果提供了新密码）
    if data.get('password'):
        user.password = generate_password_hash(data['password'])
    
    # 更新头像
    if data.get('avatar'):
        user.avatar = data['avatar']
    
    # 更新其他可选字段
    if 'is_disabled' in data:
        user.is_disabled = data['is_disabled']
    
    if 'house_id' in data:
        user.house_id = data['house_id']
    
    if 'parking_id' in data:
        user.parking_id = data['parking_id']
    
    db.session.commit()
    
    return success(user.to_dict(), "User updated successfully")

def delete_user(user_id):
    # 获取当前登录用户的ID
    current_user_id = get_jwt_identity()
    
    # 查找要删除的用户
    user = User.query.get(user_id)
    if not user:
        return error("User not found", 404)
    
    db.session.delete(user)
    db.session.commit()
    
    return success({}, "User deleted successfully")
